package com.example.voicechat

import android.annotation.SuppressLint
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.content.pm.PackageManager
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import android.view.MotionEvent
import android.text.method.ScrollingMovementMethod
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.IBinder
import android.graphics.Bitmap
import android.provider.MediaStore
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import org.json.JSONArray
import org.json.JSONObject

class MainActivity : AppCompatActivity() {

    private lateinit var tvOutput: TextView
    private lateinit var etInput: EditText
    private lateinit var btnVoiceInput: Button
    private lateinit var btnSend: Button
    private lateinit var responseTextView: TextView

    private lateinit var voiceRecognitionManager: VoiceRecognitionManager
    private var chatService: DefaultChatService? = null
    private val serviceConnection = object : ServiceConnection {
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            val binder = service as DefaultChatService.ChatBinder
            chatService = binder.getService()
        }

        override fun onServiceDisconnected(name: ComponentName?) {
            chatService = null
        }
    }

    private lateinit var imageRecognitionManager: ImageRecognitionManager
    private val CAMERA_PERMISSION_CODE = 102
    private val CAMERA_REQUEST_CODE = 103

    private var currentQuestion = ""
    private var currentAnswer = StringBuilder()
    private var historyBuilder = StringBuilder()
    private var isProcessing = false

    private val MAX_HISTORY_ROUNDS = 15  // 保留最近15轮对话
    private val conversations = mutableListOf<Pair<String, String>>()  // 存储对话历史

    @SuppressLint("ClickableViewAccessibility")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 检查并申请录音权限
        checkAndRequestPermissions()

        // 初始化视图控件
        tvOutput = findViewById(R.id.tvOutput)
        etInput = findViewById(R.id.etInput)
        btnVoiceInput = findViewById(R.id.btnVoiceInput)
        btnSend = findViewById(R.id.btnSend)
        responseTextView = findViewById(R.id.responseTextView)
        responseTextView.movementMethod = ScrollingMovementMethod.getInstance()

        // 初始化语音识别管理器（封装讯飞SDK或其他语音识别服务）
        voiceRecognitionManager = VoiceRecognitionManager(this)

        // 初始化图片识别管理器
        imageRecognitionManager = ImageRecognitionManager(this)

        // 绑定服务
        Intent(this, DefaultChatService::class.java).also { intent ->
            bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)
        }

        loadHistory()

        btnSend.setOnClickListener {
            if (isProcessing) {
                tvOutput.text = "请等待当前请求完成"
                return@setOnClickListener
            }
            isProcessing = true
            if (!isNetworkAvailable()) {
                tvOutput.text = "请检查网络连接"
                isProcessing = false
                return@setOnClickListener
            }
            val inputText = etInput.text.toString().trim()
            if (inputText.isNotEmpty()) {
                // 发送消息后清空输入框
                etInput.setText("")
                currentQuestion = inputText
                currentAnswer.clear()
                
                // 添加用户问题到历史
                historyBuilder.append("我: ").append(currentQuestion).append("\n\n")
                historyBuilder.append("AI: ")
                responseTextView.text = historyBuilder.toString()
                
                chatService?.sendMessage(inputText, object : BaseChatService.ChatCallback {
                    override fun onResponse(response: String, history: List<Pair<String, String>>) {
                        // 不再使用这个方法
                    }

                    override fun onPartialResponse(text: String, isEnd: Boolean) {
                        if (isEnd) {
                            isProcessing = false
                        }
                        runOnUiThread {
                            currentAnswer.append(text)
                            val fullText = historyBuilder.toString() + currentAnswer.toString()
                            responseTextView.text = fullText
                            
                            if (isEnd) {
                                historyBuilder.append(currentAnswer.toString()).append("\n\n")
                                currentAnswer.clear()
                            }
                            
                            // 自动滚动到底部
                            responseTextView.post {
                                val scrollAmount = responseTextView.layout.getLineTop(responseTextView.lineCount) - responseTextView.height
                                if (scrollAmount > 0) {
                                    responseTextView.scrollTo(0, scrollAmount)
                                }
                            }
                        }
                    }

                    override fun onError(error: String) {
                        isProcessing = false
                        runOnUiThread {
                            responseTextView.text = historyBuilder.toString() + "错误: $error\n\n"
                        }
                    }
                })
            }
        }

        btnVoiceInput.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    if (!hasRecordPermission()) {
                        tvOutput.text = "请先授予录音权限"
                        return@setOnTouchListener true
                    }
                    Log.d("MainActivity", "按下语音按钮")
                    btnVoiceInput.text = "松开结束"
                    tvOutput.text = "正在录音..."
                    // 清空输入框
                    etInput.setText("")
                    
                    voiceRecognitionManager.startVoiceRecognition(object : VoiceRecognitionManager.VoiceRecognitionListener {
                        override fun onResult(result: String) {
                            runOnUiThread {
                                val currentText = etInput.text.toString()
                                val newText = if (currentText.isEmpty()) result else "$currentText $result"
                                etInput.setText(newText)
                                etInput.setSelection(newText.length)
                                tvOutput.text = "识别成功"
                                
                                currentQuestion = result
                                currentAnswer.clear()
                                
                                historyBuilder.append("我: ").append(currentQuestion).append("\n\n")
                                historyBuilder.append("AI: ")
                                responseTextView.text = historyBuilder.toString()
                                
                                chatService?.sendMessage(result, object : BaseChatService.ChatCallback {
                                    override fun onResponse(response: String, history: List<Pair<String, String>>) {
                                        // 不再使用这个方法
                                    }

                                    override fun onPartialResponse(text: String, isEnd: Boolean) {
                                        runOnUiThread {
                                            currentAnswer.append(text)
                                            val fullText = historyBuilder.toString() + currentAnswer.toString()
                                            responseTextView.text = fullText
                                            
                                            if (isEnd) {
                                                historyBuilder.append(currentAnswer.toString()).append("\n\n")
                                                currentAnswer.clear()
                                            }
                                            
                                            // 自动滚动到底部
                                            responseTextView.post {
                                                val scrollAmount = responseTextView.layout.getLineTop(responseTextView.lineCount) - responseTextView.height
                                                if (scrollAmount > 0) {
                                                    responseTextView.scrollTo(0, scrollAmount)
                                                }
                                            }
                                        }
                                    }

                                    override fun onError(error: String) {
                                        runOnUiThread {
                                            responseTextView.text = historyBuilder.toString() + "错误: $error\n\n"
                                        }
                                    }
                                })
                            }
                        }

                        override fun onError(error: String) {
                            Log.e("MainActivity", "识别错误: $error")
                            runOnUiThread {
                                tvOutput.text = "语音识别错误: $error"
                                btnVoiceInput.text = getString(R.string.voice_input_hint)
                                Log.d("MainActivity", "错误UI更新完成")
                            }
                        }
                    })
                    true
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    Log.d("MainActivity", "松开语音按钮")
                    btnVoiceInput.text = getString(R.string.voice_input_hint)
                    tvOutput.text = "正在识别..."
                    voiceRecognitionManager.release()
                    Log.d("MainActivity", "语音识别资源已释放")
                    true
                }
                else -> false
            }
        }

        findViewById<Button>(R.id.btnCamera).setOnClickListener {
            LogUtils.e("MainActivity", "点击拍照按钮")
            if (hasCameraPermission()) {
                LogUtils.e("MainActivity", "已有相机权限，开始拍照")
                startCamera()
            } else {
                LogUtils.e("MainActivity", "请求相机权限")
                requestCameraPermission()
            }
        }

        // 长按清空历史
        responseTextView.setOnLongClickListener {
            clearHistory()
            true
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        when (requestCode) {
            CAMERA_PERMISSION_CODE -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    LogUtils.e("MainActivity", "相机权限已授予，开始拍照")
                    startCamera()
                } else {
                    LogUtils.e("MainActivity", "相机权限被拒绝")
                    tvOutput.text = "需要相机权限才能使用拍照功能"
                }
            }
            101 -> {
                if (grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    Log.d("MainActivity", "录音权限已授予")
                } else {
                    Log.e("MainActivity", "录音权限被拒绝")
                    tvOutput.text = "需要录音权限才能使用语音功能"
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(serviceConnection)
        voiceRecognitionManager.release()
        imageRecognitionManager.cancel()
    }

    private fun hasRecordPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            android.Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun checkAndRequestPermissions() {
        val permissions = arrayOf(
            android.Manifest.permission.RECORD_AUDIO,
            android.Manifest.permission.READ_EXTERNAL_STORAGE,
            android.Manifest.permission.WRITE_EXTERNAL_STORAGE
        )

        val notGrantedPermissions = permissions.filter {
            ContextCompat.checkSelfPermission(this, it) != PackageManager.PERMISSION_GRANTED
        }

        if (notGrantedPermissions.isNotEmpty()) {
            ActivityCompat.requestPermissions(
                this,
                notGrantedPermissions.toTypedArray(),
                101
            )
        }
    }

    private fun hasCameraPermission(): Boolean {
        return ContextCompat.checkSelfPermission(
            this,
            android.Manifest.permission.CAMERA
        ) == PackageManager.PERMISSION_GRANTED
    }

    private fun requestCameraPermission() {
        ActivityCompat.requestPermissions(
            this,
            arrayOf(android.Manifest.permission.CAMERA),
            CAMERA_PERMISSION_CODE
        )
    }

    private fun startCamera() {
        LogUtils.e("MainActivity", "开始启动相机")
        try {
            val intent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
            // 检查是否有相机应用可以处理这个 Intent
            if (intent.resolveActivity(packageManager) != null || 
                packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY).size > 0) {
                LogUtils.e("MainActivity", "找到相机应用，准备启动")
                startActivityForResult(intent, CAMERA_REQUEST_CODE)
            } else {
                LogUtils.e("MainActivity", "没有找到相机应用")
                tvOutput.text = "设备上没有可用的相机应用"
            }
        } catch (e: Exception) {
            LogUtils.e("MainActivity", "启动相机失败: ${e.message}")
            tvOutput.text = "启动相机失败: ${e.message}"
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        LogUtils.e("MainActivity", "onActivityResult: requestCode=$requestCode, resultCode=$resultCode")
        
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (resultCode == RESULT_OK) {
                val imageBitmap = data?.extras?.get("data") as? Bitmap
                if (imageBitmap != null) {
                    LogUtils.e("MainActivity", "成功获取照片，开始识别")
                    tvOutput.text = "正在识别图片..."
                    imageRecognitionManager.recognizeImage(imageBitmap, object : ImageRecognitionManager.ImageRecognitionListener {
                        override fun onResult(result: String) {
                            LogUtils.e("MainActivity", "识别成功: $result")
                            runOnUiThread {
                                val currentText = etInput.text.toString()
                                val newText = if (currentText.isEmpty()) result else "$currentText $result"
                                etInput.setText(newText)
                                etInput.setSelection(newText.length)
                                tvOutput.text = "图片识别成功，请点击发送按钮发送到AI"
                            }
                        }

                        override fun onError(error: String) {
                            LogUtils.e("MainActivity", "识别失败: $error")
                            runOnUiThread {
                                tvOutput.text = "图片识别失败: $error"
                            }
                        }

                        override fun onProgress(progress: Int) {
                            LogUtils.e("MainActivity", "识别进度: $progress%")
                            runOnUiThread {
                                tvOutput.text = "正在识别图片... $progress%"
                            }
                        }
                    })
                } else {
                    LogUtils.e("MainActivity", "没有获取到照片数据")
                    tvOutput.text = "未能获取照片"
                }
            } else {
                LogUtils.e("MainActivity", "拍照被取消或失败")
                tvOutput.text = "拍照被取消"
            }
        }
    }

    private fun addConversation(question: String, answer: String) {
        conversations.add(Pair(question, answer))
        if (conversations.size > MAX_HISTORY_ROUNDS) {
            conversations.removeAt(0)  // 移除最旧的对话
        }
        updateHistoryDisplay()
    }

    private fun updateHistoryDisplay() {
        historyBuilder.clear()
        conversations.forEach { (question, answer) ->
            historyBuilder.append("我: ").append(question).append("\n\n")
            historyBuilder.append("AI: ").append(answer).append("\n\n")
        }
        responseTextView.text = historyBuilder.toString()
    }

    private fun clearHistory() {
        conversations.clear()
        currentQuestion = ""
        currentAnswer.clear()
        historyBuilder.clear()
        responseTextView.text = ""
    }

    private fun isNetworkAvailable(): Boolean {
        val connectivityManager = getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkCapabilities = connectivityManager.activeNetwork ?: return false
        val actNw = connectivityManager.getNetworkCapabilities(networkCapabilities) ?: return false
        return when {
            actNw.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
            actNw.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
            actNw.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> true
            else -> false
        }
    }

    private fun saveHistory() {
        val json = JSONArray().apply {
            conversations.forEach { (question, answer) ->
                put(JSONObject().apply {
                    put("question", question)
                    put("answer", answer)
                })
            }
        }
        
        getSharedPreferences("chat_history", Context.MODE_PRIVATE)
            .edit()
            .putString("history", json.toString())
            .apply()
    }

    private fun loadHistory() {
        clearHistory()  // 清空当前历史
    }

    override fun onPause() {
        super.onPause()
        saveHistory()
    }
} 